<template>
    <div class="component-config-manager">
        <el-card class="config-header">
            <template #header>
                <div class="header-content">
                    <h2>组件配置管理器</h2>
                    <p>独立管理每个组件的配置和样式</p>
                </div>
            </template>
        </el-card>

        <el-row :gutter="20" class="config-content">
            <!-- 组件列表 -->
            <el-col :span="8">
                <el-card class="component-list">
                    <template #header>
                        <div class="card-header">
                            <span>组件列表</span>
                            <el-button type="primary" size="small" @click="refreshComponents">刷新</el-button>
                        </div>
                    </template>

                    <el-menu :default-active="activeComponent" @select="selectComponent" class="component-menu">
                        <el-menu-item v-for="component in componentList" :key="component.name" :index="component.name">
                            <el-icon>
                                <Monitor />
                            </el-icon>
                            <span>{{ component.displayName }}</span>
                            <el-tag v-if="component.hasConfig" size="small" type="success" style="margin-left: auto;">
                                已配置
                            </el-tag>
                        </el-menu-item>
                    </el-menu>
                </el-card>
            </el-col>

            <!-- 配置详情 -->
            <el-col :span="16">
                <el-card v-if="activeComponent" class="config-detail">
                    <template #header>
                        <div class="card-header">
                            <span>{{ getComponentDisplayName(activeComponent) }} 配置</span>
                            <div class="header-actions">
                                <el-button type="success" size="small" @click="saveConfig">保存配置</el-button>
                                <el-button type="warning" size="small" @click="resetConfig">重置配置</el-button>
                                <el-button type="info" size="small" @click="exportConfig">导出配置</el-button>
                                <el-button type="primary" size="small" @click="importConfig">导入配置</el-button>
                            </div>
                        </div>
                    </template>

                    <el-tabs v-model="activeTab" type="card">
                        <!-- 容器配置 -->
                        <el-tab-pane label="容器配置" name="container">
                            <el-form :model="currentConfig.container" label-width="120px">
                                <el-form-item label="桌面端高度">
                                    <el-input-number v-model="currentConfig.container.height.desktop" :min="300"
                                        :max="600" />
                                </el-form-item>
                                <el-form-item label="平板端高度">
                                    <el-input-number v-model="currentConfig.container.height.tablet" :min="250"
                                        :max="500" />
                                </el-form-item>
                                <el-form-item label="移动端高度">
                                    <el-input-number v-model="currentConfig.container.height.mobile" :min="200"
                                        :max="400" />
                                </el-form-item>
                                <el-form-item label="内边距">
                                    <el-input v-model="currentConfig.container.padding" />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>

                        <!-- 图表配置 -->
                        <el-tab-pane v-for="chart in getChartConfigs()" :key="chart.name" :label="chart.displayName"
                            :name="chart.name">
                            <el-form :model="currentConfig[chart.name]" label-width="120px">
                                <el-form-item label="标题">
                                    <el-input v-model="currentConfig[chart.name].title.text" />
                                </el-form-item>
                                <el-form-item label="标题字体大小">
                                    <el-input-number v-model="currentConfig[chart.name].title.fontSize" :min="12"
                                        :max="24" />
                                </el-form-item>
                                <el-form-item label="标题颜色">
                                    <el-color-picker v-model="currentConfig[chart.name].title.color" />
                                </el-form-item>

                                <!-- 动态配置项 -->
                                <template v-if="chart.name === 'conversionFunnel'">
                                    <el-form-item label="漏斗宽度">
                                        <el-input v-model="currentConfig[chart.name].funnel.width" />
                                    </el-form-item>
                                    <el-form-item label="漏斗高度">
                                        <el-input v-model="currentConfig[chart.name].funnel.height" />
                                    </el-form-item>
                                </template>

                                <template v-if="chart.name === 'utilizationRanking'">
                                    <el-form-item label="柱状图宽度">
                                        <el-input v-model="currentConfig[chart.name].bar.width" />
                                    </el-form-item>
                                </template>

                                <template v-if="chart.name === 'revenueTrend'">
                                    <el-form-item label="折线图标记大小">
                                        <el-input-number v-model="currentConfig[chart.name].line.symbolSize" :min="4"
                                            :max="12" />
                                    </el-form-item>
                                </template>

                                <template v-if="chart.name === 'serviceDistribution'">
                                    <el-form-item label="饼图半径">
                                        <el-input v-model="currentConfig[chart.name].pie.radius[0]" placeholder="内半径" />
                                        <el-input v-model="currentConfig[chart.name].pie.radius[1]" placeholder="外半径" />
                                    </el-form-item>
                                </template>
                            </el-form>
                        </el-tab-pane>

                        <!-- 数据配置 -->
                        <el-tab-pane label="数据配置" name="data">
                            <el-alert title="数据配置" description="这里可以配置图表的数据源和数据结构" type="info" :closable="false"
                                style="margin-bottom: 20px;" />

                            <el-button type="primary" @click="previewData">预览数据</el-button>
                            <el-button type="success" @click="generateSampleData">生成示例数据</el-button>
                        </el-tab-pane>

                        <!-- 样式配置 -->
                        <el-tab-pane label="样式配置" name="style">
                            <el-alert title="样式配置" description="样式配置在独立的CSS文件中管理，可以在这里查看和编辑" type="info"
                                :closable="false" style="margin-bottom: 20px;" />

                            <el-button type="primary" @click="openStyleEditor">打开样式编辑器</el-button>
                            <el-button type="success" @click="previewStyle">预览样式</el-button>
                        </el-tab-pane>
                    </el-tabs>
                </el-card>

                <el-card v-else class="no-selection">
                    <div class="no-selection-content">
                        <el-icon size="48" color="#909399"><Select /></el-icon>
                        <p>请选择一个组件进行配置</p>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 导入配置对话框 -->
        <el-dialog v-model="importDialogVisible" title="导入配置" width="500px">
            <el-form>
                <el-form-item label="配置JSON">
                    <el-input v-model="importConfigText" type="textarea" :rows="10" placeholder="请输入配置JSON" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="importDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmImport">确认导入</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Monitor, Select } from '@element-plus/icons-vue'
import componentManager from './ComponentManager.js'

// 响应式数据
const activeComponent = ref('')
const activeTab = ref('container')
const currentConfig = ref({})
const importDialogVisible = ref(false)
const importConfigText = ref('')

// 组件列表
const componentList = computed(() => {
    const names = componentManager.getComponentNames()
    return names.map(name => ({
        name,
        displayName: getComponentDisplayName(name),
        hasConfig: true,
        hasStyle: !!componentManager.getStylePath(name)
    }))
})

// 获取组件显示名称
const getComponentDisplayName = (name) => {
    const nameMap = {
        'BusinessAnalysis': '经营分析',
        'CustomerInsight': '客户洞察',
        'WarningMonitor': '预警监控'
    }
    return nameMap[name] || name
}

// 获取图表配置列表
const getChartConfigs = () => {
    if (!activeComponent.value) return []

    const config = componentManager.getConfig(activeComponent.value)
    const chartNames = Object.keys(config).filter(key => key !== 'container')

    return chartNames.map(name => ({
        name,
        displayName: getChartDisplayName(name)
    }))
}

// 获取图表显示名称
const getChartDisplayName = (name) => {
    const nameMap = {
        'conversionFunnel': '转化率漏斗图',
        'utilizationRanking': '技师利用率排行榜',
        'revenueTrend': '营收趋势图',
        'serviceDistribution': '服务项目分布图',
        'customerValue': '客户价值图',
        'serviceHeatmap': '服务热力图',
        'consumptionFrequency': '消费频次分析',
        'ageDistribution': '年龄分布图',
        'noShowChart': '爽约率监控',
        'resourceChart': '资源监控',
        'alertStats': '预警统计'
    }
    return nameMap[name] || name
}

// 选择组件
const selectComponent = (name) => {
    activeComponent.value = name
    currentConfig.value = JSON.parse(JSON.stringify(componentManager.getConfig(name)))
    activeTab.value = 'container'
}

// 保存配置
const saveConfig = async () => {
    try {
        componentManager.updateConfig(activeComponent.value, currentConfig.value)
        ElMessage.success('配置保存成功')
    } catch (error) {
        ElMessage.error('配置保存失败')
    }
}

// 重置配置
const resetConfig = async () => {
    try {
        await ElMessageBox.confirm('确定要重置配置吗？这将恢复默认设置。', '确认重置', {
            type: 'warning'
        })

        componentManager.resetConfig(activeComponent.value)
        currentConfig.value = JSON.parse(JSON.stringify(componentManager.getConfig(activeComponent.value)))
        ElMessage.success('配置已重置')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('重置失败')
        }
    }
}

// 导出配置
const exportConfig = () => {
    const config = componentManager.exportConfig(activeComponent.value)
    if (config) {
        const blob = new Blob([config], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${activeComponent.value}_config.json`
        a.click()
        URL.revokeObjectURL(url)
        ElMessage.success('配置导出成功')
    }
}

// 导入配置
const importConfig = () => {
    importDialogVisible.value = true
    importConfigText.value = ''
}

// 确认导入
const confirmImport = () => {
    if (!importConfigText.value.trim()) {
        ElMessage.warning('请输入配置JSON')
        return
    }

    try {
        const success = componentManager.importConfig(activeComponent.value, importConfigText.value)
        if (success) {
            currentConfig.value = JSON.parse(JSON.stringify(componentManager.getConfig(activeComponent.value)))
            importDialogVisible.value = false
            ElMessage.success('配置导入成功')
        } else {
            ElMessage.error('配置导入失败')
        }
    } catch (error) {
        ElMessage.error('JSON格式错误')
    }
}

// 刷新组件列表
const refreshComponents = () => {
    ElMessage.success('组件列表已刷新')
}

// 预览数据
const previewData = () => {
    ElMessage.info('数据预览功能开发中...')
}

// 生成示例数据
const generateSampleData = () => {
    ElMessage.info('示例数据生成功能开发中...')
}

// 打开样式编辑器
const openStyleEditor = () => {
    ElMessage.info('样式编辑器功能开发中...')
}

// 预览样式
const previewStyle = () => {
    ElMessage.info('样式预览功能开发中...')
}

// 组件挂载
onMounted(() => {
    if (componentList.value.length > 0) {
        selectComponent(componentList.value[0].name)
    }
})
</script>

<style scoped>
.component-config-manager {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.config-header {
    margin-bottom: 20px;
}

.header-content h2 {
    margin: 0 0 8px 0;
    color: #303133;
}

.header-content p {
    margin: 0;
    color: #909399;
}

.config-content {
    margin-bottom: 20px;
}

.component-list {
    height: fit-content;
}

.component-menu {
    border: none;
}

.component-menu .el-menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
}

.config-detail {
    min-height: 600px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    gap: 8px;
}

.no-selection {
    min-height: 600px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.no-selection-content {
    text-align: center;
    color: #909399;
}

.no-selection-content p {
    margin: 16px 0 0 0;
    font-size: 16px;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-tabs {
    margin-top: 20px;
}
</style>